package smartcampus.scjava.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import smartcampus.scjava.POJO.DO.Smartuser;
import smartcampus.scjava.POJO.DTO.SmartuserDTO;
import smartcampus.scjava.service.SmartuserService;
import smartcampus.scjava.mapper.SmartuserMapper;
import org.springframework.stereotype.Service;
import smartcampus.scjava.utils.JwtUtils;
import smartcampus.scjava.utils.MD5Utils;
import smartcampus.scjava.utils.PropertyUtils;
import smartcampus.scjava.utils.RedisUtils;

import javax.annotation.Resource;
import java.util.Date;

import static smartcampus.scjava.custom.Constant.REFRESH_TOKEN_ACTIVE;

/**
* @author 北煜
* @description 针对表【smartuser】的数据库操作Service实现
* @createDate 2023-10-17 21:32:25
*/
@Service
public class SmartuserServiceImpl extends ServiceImpl<SmartuserMapper, Smartuser>
    implements SmartuserService{

    @Resource
    SmartuserMapper smartuserMapper;

    /**
     * 根据用户名在数据库中查找用户
     */

    @Override
    public SmartuserDTO getUserByUsername(String username) {
        return PropertyUtils.doToDto(smartuserMapper.getUserByUsername(username), SmartuserDTO.class);
    }

    /**
     *
     * @param username 用户名
     * @param password 用户密码
     * @return 返回响应
     */
    @Override
    public String checkLogin(String username, String password) {
        String encryptedPwd = MD5Utils.getMd5UserPwd(username,password);
        Smartuser user = smartuserMapper.getUserByUsername(username);
        if (user == null) {
            return "用户名不存在";
        }
        if ( !encryptedPwd.equals(user.getPassword()) ) {
            return "密码错误！";
        }
        Date date = new Date();
        String time = date.toString();
        String token = JwtUtils.creatToken(username,time);
        RedisUtils.put(username,time,REFRESH_TOKEN_ACTIVE);
        return token;
    }

    /**
     * 进行简单的注册，没有联立其他表情况，后续可以改进
     *
     * @param username 用户名
     * @param password 用户密码
     * @return 返回用户初始完成否
     */
    @Override
    public Long register(String username, String password) {
        Date date = new Date();
        Smartuser user = new Smartuser();
        user.setUsername(username);
        String encryptedPwd = MD5Utils.getMd5UserPwd(username,password);
        user.setPassword(encryptedPwd);
        user.setCreateTime(date);
        user.setUpdateTime(date);
        System.out.println(user);
        return smartuserMapper.insertById(user);
    }
}




